package cn.edu.nit.security;

import cn.edu.nit.security.entity.LoginUser;
import cn.edu.nit.sys.dto.UserDTO;
import cn.edu.nit.sys.entity.Role;
import cn.edu.nit.sys.entity.User;
import cn.edu.nit.sys.mapper.UserMapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectUserUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new UsernameNotFoundException("用户不存在");
        }
        UserDTO userList = userMapper.login(username);
        return new LoginUser(user.getId(), user.getUsername(), new BCryptPasswordEncoder().encode(user.getPassword()),
                user.getRoleId().toString(), AuthorityUtils.commaSeparatedStringToAuthorityList(userList.getRole()));
    }
}
